<template>
  <div class="post-loan-inspection">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>贷后检查</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddPlan">新增检查计划</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="检查状态">
          <el-select v-model="searchForm.status" placeholder="请选择检查状态" clearable>
            <el-option label="待检查" value="pending"></el-option>
            <el-option label="检查中" value="processing"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已逾期" value="overdue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="loanNo" label="贷款编号" width="180"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
        <el-table-column prop="planDate" label="计划检查日期" width="120"></el-table-column>
        <el-table-column prop="inspector" label="检查人员" width="120"></el-table-column>
        <el-table-column prop="type" label="检查类型" width="120">
          <template #default="scope">
            {{ getInspectionType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="method" label="检查方式" width="120">
          <template #default="scope">
            {{ getInspectionMethod(scope.row.method) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="检查状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="result" label="检查结果" width="120">
          <template #default="scope">
            <el-tag :type="getResultType(scope.row.result)">{{ getResultText(scope.row.result) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="actualDate" label="实际检查日期" width="120"></el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleStart(scope.row)" :disabled="scope.row.status !== 'pending'">开始检查</el-button>
            <el-button link type="primary" @click="handleReport(scope.row)" :disabled="scope.row.status !== 'completed'">检查报告</el-button>
            <el-button link type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.status === 'completed'">编辑</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" :disabled="scope.row.status === 'completed'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑检查计划对话框 -->
    <el-dialog 
      v-model="planDialogVisible" 
      :title="planForm.id ? '编辑检查计划' : '新增检查计划'"
      width="600px"
    >
      <el-form :model="planForm" label-width="100px" :rules="planRules" ref="planFormRef">
        <el-form-item label="贷款编号" prop="loanNo">
          <el-select v-model="planForm.loanNo" placeholder="请选择贷款" filterable style="width: 100%">
            <el-option
              v-for="item in loanOptions"
              :key="item.loanNo"
              :label="`${item.loanNo} - ${item.customerName}`"
              :value="item.loanNo"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查类型" prop="type">
          <el-select v-model="planForm.type" placeholder="请选择检查类型" style="width: 100%">
            <el-option label="定期检查" value="regular"></el-option>
            <el-option label="不定期检查" value="irregular"></el-option>
            <el-option label="专项检查" value="special"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查方式" prop="method">
          <el-select v-model="planForm.method" placeholder="请选择检查方式" style="width: 100%">
            <el-option label="现场检查" value="onsite"></el-option>
            <el-option label="非现场检查" value="offsite"></el-option>
            <el-option label="视频检查" value="video"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期" prop="planDate">
          <el-date-picker v-model="planForm.planDate" type="date" placeholder="选择计划检查日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="检查人员" prop="inspector">
          <el-select v-model="planForm.inspector" placeholder="请选择检查人员" style="width: 100%">
            <el-option
              v-for="item in inspectorOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查内容" prop="content">
          <el-input v-model="planForm.content" type="textarea" rows="4" placeholder="请输入检查内容"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="planForm.remark" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="planDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPlan">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 检查报告对话框 -->
    <el-dialog v-model="reportDialogVisible" title="检查报告" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="贷款编号">{{ currentReport.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentReport.customerName }}</el-descriptions-item>
        <el-descriptions-item label="检查类型">{{ getInspectionType(currentReport.type) }}</el-descriptions-item>
        <el-descriptions-item label="检查方式">{{ getInspectionMethod(currentReport.method) }}</el-descriptions-item>
        <el-descriptions-item label="计划检查日期">{{ currentReport.planDate }}</el-descriptions-item>
        <el-descriptions-item label="实际检查日期">{{ currentReport.actualDate }}</el-descriptions-item>
        <el-descriptions-item label="检查人员">{{ currentReport.inspector }}</el-descriptions-item>
        <el-descriptions-item label="检查结果">
          <el-tag :type="getResultType(currentReport.result)">{{ getResultText(currentReport.result) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="检查内容" :span="2">{{ currentReport.content }}</el-descriptions-item>
        <el-descriptions-item label="检查发现" :span="2">{{ currentReport.findings }}</el-descriptions-item>
        <el-descriptions-item label="整改建议" :span="2">{{ currentReport.suggestions }}</el-descriptions-item>
        <el-descriptions-item label="跟进措施" :span="2">{{ currentReport.followUp }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentReport.remark }}</el-descriptions-item>
      </el-descriptions>
      <div class="report-images" v-if="currentReport.images && currentReport.images.length">
        <h4>现场照片</h4>
        <el-image
          v-for="(image, index) in currentReport.images"
          :key="index"
          :src="image"
          :preview-src-list="currentReport.images"
          fit="cover"
          class="report-image"
        ></el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { postloanInspectionApi } from '@/api/postloan'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  loanNo: '',
  customerName: '',
  status: '',
  dateRange: []
})

// 检查计划表单
const planDialogVisible = ref(false)
const planFormRef = ref(null)
const planForm = reactive({
  id: '',
  loanNo: '',
  type: '',
  method: '',
  planDate: '',
  inspector: '',
  content: '',
  remark: ''
})

// 表单校验规则
const planRules = {
  loanNo: [{ required: true, message: '请选择贷款', trigger: 'change' }],
  type: [{ required: true, message: '请选择检查类型', trigger: 'change' }],
  method: [{ required: true, message: '请选择检查方式', trigger: 'change' }],
  planDate: [{ required: true, message: '请选择计划检查日期', trigger: 'change' }],
  inspector: [{ required: true, message: '请选择检查人员', trigger: 'change' }],
  content: [{ required: true, message: '请输入检查内容', trigger: 'blur' }]
}

// 贷款选项
const loanOptions = ref([])

// 检查人员选项
const inspectorOptions = ref([])

// 检查报告对话框
const reportDialogVisible = ref(false)
const currentReport = ref({})

// 获取检查类型文本
const getInspectionType = (type) => {
  const types = {
    regular: '定期检查',
    irregular: '不定期检查',
    special: '专项检查'
  }
  return types[type] || '未知'
}

// 获取检查方式文本
const getInspectionMethod = (method) => {
  const methods = {
    onsite: '现场检查',
    offsite: '非现场检查',
    video: '视频检查'
  }
  return methods[method] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'info',
    processing: 'warning',
    completed: 'success',
    overdue: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待检查',
    processing: '检查中',
    completed: '已完成',
    overdue: '已逾期'
  }
  return texts[status] || '未知'
}

// 获取结果类型
const getResultType = (result) => {
  const types = {
    normal: 'success',
    attention: 'warning',
    risk: 'danger'
  }
  return types[result] || 'info'
}

// 获取结果文本
const getResultText = (result) => {
  const texts = {
    normal: '正常',
    attention: '需关注',
    risk: '风险'
  }
  return texts[result] || '未知'
}

// 查询
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取数据
const fetchData = () => {
  loading.value = true
  
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    loanNo: searchForm.loanNo,
    customerName: searchForm.customerName,
    status: searchForm.status,
    startDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[0] : '',
    endDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[1] : ''
  }
  
  postloanInspectionApi.getList(params).then(res => {
    tableData.value = res.data.rows
    total.value = res.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 获取贷款选项
const fetchLoanOptions = () => {
  // 模拟API调用
  setTimeout(() => {
    loanOptions.value = Array.from({ length: 10 }, (_, index) => ({
      loanNo: `LOAN${String(2023000 + index + 1).padStart(7, '0')}`,
      customerName: `客户${index + 1}`
    }))
  }, 300)
}

// 获取检查人员选项
const fetchInspectorOptions = () => {
  // 模拟API调用
  setTimeout(() => {
    inspectorOptions.value = Array.from({ length: 5 }, (_, index) => ({
      id: index + 1,
      name: `检查员${index + 1}`
    }))
  }, 300)
}

// 新增检查计划
const handleAddPlan = () => {
  planForm.id = ''
  planForm.loanNo = ''
  planForm.type = ''
  planForm.method = ''
  planForm.planDate = ''
  planForm.inspector = ''
  planForm.content = ''
  planForm.remark = ''
  
  planDialogVisible.value = true
  fetchLoanOptions()
  fetchInspectorOptions()
}

// 编辑检查计划
const handleEdit = (row) => {
  Object.assign(planForm, row)
  planDialogVisible.value = true
  fetchLoanOptions()
  fetchInspectorOptions()
}

// 提交检查计划
const submitPlan = () => {
  planFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      
      const formData = {
        loanNo: planForm.loanNo,
        planDate: planForm.planDate,
        inspector: planForm.inspector,
        type: planForm.type,
        remark: planForm.remark
      }
      
      if (planForm.id) {
        // 更新
        postloanInspectionApi.update({
          id: planForm.id,
          ...formData
        }).then(() => {
          ElMessage.success('更新成功')
          planDialogVisible.value = false
          fetchData()
        }).finally(() => {
          loading.value = false
        })
      } else {
        // 新增
        postloanInspectionApi.add(formData).then(() => {
          ElMessage.success('添加成功')
          planDialogVisible.value = false
          fetchData()
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 删除检查计划
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该检查计划吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    postloanInspectionApi.delete(row.id).then(() => {
      ElMessage.success('删除成功')
      fetchData()
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {})
}

// 开始检查
const handleStart = (row) => {
  loading.value = true
  postloanInspectionApi.getDetail(row.id).then(res => {
    const detail = res.data
    currentReport.value = {
      ...row,
      content: detail.content,
      findings: detail.findings,
      suggestions: detail.suggestions,
      followUp: detail.followUp,
      remark: detail.remark,
      images: detail.images
    }
    reportDialogVisible.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 查看检查报告
const handleReport = (row) => {
  loading.value = true
  postloanInspectionApi.getDetail(row.id).then(res => {
    const detail = res.data
    currentReport.value = {
      ...row,
      content: detail.content,
      findings: detail.findings,
      suggestions: detail.suggestions,
      followUp: detail.followUp,
      remark: detail.remark,
      images: detail.images
    }
    reportDialogVisible.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.post-loan-inspection {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.report-images {
  margin-top: 20px;
}

.report-image {
  width: 120px;
  height: 120px;
  margin-right: 10px;
  margin-bottom: 10px;
}
</style> 